package pluginMain;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.inventory.Inventory;

public class DialogEvent implements Listener {
	@EventHandler
	public void onOpenInventory(InventoryOpenEvent event) {
		Inventory openedInv = event.getInventory();
		Player targetPlayer = (Player) event.getPlayer();
		Dialog targetDialog = DeliayGUI.ManagerInstance.getDialog(openedInv);
		
		if (targetDialog != null) {
			DeliayGUI.ManagerInstance.getListener(targetDialog).OpenDialog(targetDialog, targetPlayer);
		}
	}
	
	@EventHandler
	public void onPlayerClickSlot(InventoryClickEvent event){
		Inventory openedInv = event.getInventory();
		Player targetPlayer = (Player) event.getWhoClicked();
		Dialog targetDialog = DeliayGUI.ManagerInstance.getDialog(openedInv);

		if (targetDialog != null) {
			DeliayGUI.ManagerInstance.getListener(targetDialog).PlayerClickSlot(targetPlayer, targetDialog, event.getRawSlot());
		}
	}
	
	@EventHandler
	public void onPlayerClickItem(InventoryPickupItemEvent event){
		Inventory openedInv = event.getInventory();
		Player targetPlayer = (Player) event.getItem().getNearbyEntities(2, 2, 2).get(0);
		Dialog targetDialog = DeliayGUI.ManagerInstance.getDialog(openedInv);

		if (targetDialog != null) {
			DeliayGUI.ManagerInstance.getListener(targetDialog).PlayerClickItem(targetPlayer, targetDialog, event.getItem().getItemStack());
		}
	}
	
	@EventHandler
	public void onPlayerTakeItem(InventoryMoveItemEvent event){
		Inventory openedInv = event.getSource();
		Player targetPlayer = (Player) event.getDestination().getViewers().get(0);
		Dialog targetDialog = DeliayGUI.ManagerInstance.getDialog(openedInv);

		if (targetDialog != null) {
			DeliayGUI.ManagerInstance.getListener(targetDialog).PlayerClickItem(targetPlayer, targetDialog, event.getItem());
		}
	}
	
	@EventHandler
	private void onPlayerCloseDialog(InventoryCloseEvent event){
		Inventory openedInv = event.getInventory();
		Player targetPlayer = (Player) event.getPlayer();
		Dialog targetDialog = DeliayGUI.ManagerInstance.getDialog(openedInv);
		
		if (targetDialog != null) {
			DeliayGUI.ManagerInstance.getListener(targetDialog).CloseDialog(targetDialog, targetPlayer);
		}
	}
}
